package com.demo.test.tcp;

import com.alibaba.fastjson.JSON;
import org.junit.Test;

import java.io.*;
import java.net.DatagramPacket;
import java.net.Socket;
import java.util.Arrays;
import java.util.List;

public class ServerReaderRunnable implements Runnable{
    private Socket socket;
    public ServerReaderRunnable(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run() {
        try {
//            // 3、从socket通信管道中得到一个字节输入流
//            InputStream is = socket.getInputStream();
//            // 4、把字节输入流包装成缓冲字符输入流进行消息的接收
//            BufferedReader br = new BufferedReader(new InputStreamReader(is));
//
//
//            // 5、按照行读取消息
//            String msg;
//            while ((msg = br.readLine()) != null){
//                System.out.println(socket.getRemoteSocketAddress() + "说了：: " + msg);
//            }

            InputStream inputStream = socket.getInputStream();
            byte[] buffer = new byte[1024]; // 缓冲区大小
            int bytesRead;

            while ((bytesRead = inputStream.read(buffer)) > 0) { // 循环读取数据，直到没有更多数据可读
                if (bytesRead > 0) {
                    byte[] data = new byte[bytesRead];
                    System.arraycopy(buffer, 0, data, 0, bytesRead);
                    String hexString = bytesToHex(data);
                    System.out.println("Received hex data: " + hexString);
                    RadarTest radarTest = new RadarTest();
                    RadarVehicleInfoBO radarVehicleInfoBO = radarTest.handleRadarProtocol(hexString);
                    System.out.println(JSON.toJSONString(radarVehicleInfoBO));
                }
            }

            inputStream.close();
            socket.close();

        } catch (Exception e) {
            System.out.println(socket.getRemoteSocketAddress() + "下线了！！！");
        }
    }




    /**
     * 字节数组转换成十六进制
     * @param bytes
     * @return
     */
    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex).append(" ");
        }
        return hexString.toString();
    }


}